package org.atlas.framework.util;

import org.atlas.framework.ConfigConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 配置文件操作
 *
 * Created by suxinjie on 2017/3/5.
 */
public class PropsUtil {

    private static final Logger logger = LoggerFactory.getLogger(PropsUtil.class);

    public static Properties loadProps(String fileName) {
        Properties properties = null;
        InputStream inputStream = null;

        try {
            if (StringUtil.isEmpty(fileName)) {
                throw new IllegalArgumentException();
            }

            if (fileName.lastIndexOf(ConfigConstant.DEFAULT_CONFIG_FILE_SUFFIX) == -1) {
                fileName += ConfigConstant.DEFAULT_CONFIG_FILE_SUFFIX;
            }

            inputStream = ClassUtil.getClassLoader().getResourceAsStream(fileName);

            if (inputStream == null) {
                throw new FileNotFoundException(fileName + " file is not found");
            }

            properties = new Properties();
            properties.load(inputStream);
        } catch (Exception e) {
            logger.error("load properties file failure", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("close input stream failure", e);
                }
            }
        }

        return properties;
    }

    /**
     * 获取字符型值,默认为空字符串
     */
    public static String getString(Properties properties, String key) {
        return getString(properties, key, "");
    }

    /**
     * 获取字符型值,可设置默认值
     */
    public static String getString(Properties properties, String key, String defaultValue) {
        String value = defaultValue;
        if (properties.containsKey(key)) {
            value = properties.getProperty(key);
        }
        return value;
    }

    /**
     * 获取数值型值,默认值为0
     */
    public static int getInt(Properties properties, String key) {
        return getInt(properties, key, 0);
    }

    /**
     * 获取数值型值,可设置默认值
     */
    public static int getInt(Properties properties, String key, int defaultValue) {
        int value = defaultValue;
        if (properties.containsKey(key)) {
            value = CastUtil.castInt(properties.getProperty(key));
        }
        return value;
    }

    /**
     * 获取布尔值,默认为false
     */
    public static boolean getBoolean(Properties properties, String key) {
        return getBoolean(properties, key, false);
    }

    /**
     * 获取布尔值,可设置默认值
     */
    public static boolean getBoolean(Properties properties, String key, boolean defaultValue) {
        boolean value = defaultValue;
        if (properties.containsKey(key)) {
            value = CastUtil.castBoolean(properties.getProperty(key));
        }
        return value;
    }


}
